package com.becca.cake.service.sms.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.becca.cake.core.excel.excelReader.ExcelReaderByJxlUtil;
import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.core.sms.SMSHelper;
import com.becca.cake.core.sms.message.SmsUserMass;
import com.becca.cake.dao.sms.SmsDAO;
import com.becca.cake.dao.users.UserManagerDAO;
import com.becca.cake.model.sms.SmsContentModel;
import com.becca.cake.model.sms.SmsUserModel;
import com.becca.cake.model.users.UsersModel;
import com.becca.cake.service.sms.ISmsService;

/**
 * 短信管理业务层
 * @copyright  尊星(上海)信息科技有限公司
 * @author hejinguo
 * @date 2016年9月2日 下午12:22:54
 */
@Service
public class SmsServiceImpl implements ISmsService {
    @Autowired
    private SmsDAO         smsDAO;
    @Autowired
    private UserManagerDAO userManagerDAO;

    @Override
    public List<SmsUserModel> selectAllSms(Map<String, Object> map) {
        return this.smsDAO.selectAllSms(map);
    }

    @Override
    public Long selectAllSmsCount(Map<String, Object> map) {
        return this.smsDAO.selectAllSmsCount(map);
    }

    @Override
    public String importExcelUserPhone(MultipartFile file) {
        if (file == null) {
            throw new ServiceException("导入Excel文件对象为空!");
        }
        InputStream stream = null;
        try {
            stream = file.getInputStream();
        } catch (IOException e) {
            throw new ServiceException("导入Excel IO流异常!");
        }
        ExcelReaderByJxlUtil readerByJxlUtil = new ExcelReaderByJxlUtil();
        return readerByJxlUtil.readExcelToPresentScore(stream);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void addSendSms(SmsUserModel smsUserModel, String userName) {
        boolean result = false;
        //step1:验证用户信息
        SmsUserModel.validateAddSendSmsParam(smsUserModel);
        //step2:添加短信内容
        SmsContentModel contentModel = new SmsContentModel();
        contentModel.setContent(smsUserModel.getContent());
        this.smsDAO.addSmsContent(contentModel);
        smsUserModel.setSmsIontentId(contentModel.getId());
        smsUserModel.setCreatedName(userName);
        //step3:发送短信
        if (smsUserModel.getGateWay() == 0 || smsUserModel.getGateWay() == 1) {//单个或批量发送
            SmsUserMass userMass = new SmsUserMass(smsUserModel.getPhoneNumber(),
                smsUserModel.getContent());
            if (SMSHelper.sendMessageList(userMass)) {//批量发送短信
                result = true;
                //step4:添加短信用户信息
                smsUserModel.setSmsStatus(Byte.valueOf("1"));
                this.smsDAO.addSmsUser(smsUserModel);
            }
        } else if (smsUserModel.getGateWay() == 2) {//全部用户群发
            //step5:查询全部用户
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("userType", "0,1");
            paramMap.put("status", "0");
            List<UsersModel> listUsers = this.userManagerDAO.selectAllUsableUsers(paramMap);
            if (listUsers != null && listUsers.size() > 0) {
                int batch = 0;
                String phoneStr = "";
                for (int i = 0, n = listUsers.size(); i < n; i++) {
                    UsersModel usersModel = listUsers.get(i);
                    phoneStr += usersModel.getMobileNo() + ",";
                    batch++;
                    //每100个用户批量提交一次。
                    if (batch >= 100) {
                        phoneStr = phoneStr.substring(0, phoneStr.length() - 1);
                        SmsUserMass userMass = new SmsUserMass(phoneStr, smsUserModel.getContent());
                        if (SMSHelper.sendMessageList(userMass)) {//批量发送短信
                            result = true;
                        }
                        phoneStr = "";
                        batch = 0;
                    }
                }
                if (StringUtils.isNotEmpty(phoneStr)) {//剩下最后不满100条
                    phoneStr = phoneStr.substring(0, phoneStr.length() - 1);
                    SmsUserMass userMass = new SmsUserMass(phoneStr, smsUserModel.getContent());
                    if (SMSHelper.sendMessageList(userMass)) {//批量发送短信
                        result = true;
                    }
                }
                //step6:添加短信用户信息
                if (result) {
                    smsUserModel.setSmsStatus(Byte.valueOf("1"));
                    this.smsDAO.addSmsUser(smsUserModel);
                }
            }
        }
        //step7:判断短信是否发送成功
        if (!result) {
            throw new ServiceException("短信发送失败!");
        }
    }
}
